<?php

class Luck
{
    private $luckGoods;


    public function __construct($param = [])
    {
        $this->luckGoods = $param;
    }

    /**
     * @throws Exception
     */
    public function begins()
    {
        if (empty($this->luckGoods)) {
            throw new Exception('盲盒内无商品 , 无法抽奖');
        }
        $result = $this->createRand($this->luckGoods);
        //根据概率获取奖项id
        $rid = $this->get_rand($result);
        return $this->luckGoods[$rid - 1];
    }

    // 整理对应的编号以及概率
    protected function createRand($prizeArr): array
    {
        $newArr = [];
        foreach ($prizeArr as & $val) {
            $newArr[$val['id']] = $val['probability'];
        }
        return $newArr;
    }

    /**
     * 生成概率
     * @param $proArr //概率列表
     * @return array|int|string
     */
    protected function get_rand($proArr)
    {
        $result = [];
        //概率数组的总概率
        $proSum = array_sum($proArr);
        //概率数组循环
        $start = mt_rand(1, 10);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand($start, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
}
